#! /usr/bin/python
# -*- coding: utf-8 -*-
from elixir import *
import httplib
import random


""" 
Debug=0 # None
Debug=1 # ERRORS
Debug=2 # WARNINGS
Debug=3 # ALERTS
Debug=4 # INFO
"""

class Banner():
  responseHeaders=None
  ip=None
  port=80
  timeout=2
  debug=4  
  
  def __init__(self):
    pass

  def setIP(self,ip):
    self.ip=ip
  
  def validIP(self):
    print self.ip
    ipocts=self.ip.split(".")
    if(len(ipocts)==4):
      if(self.debug>=4):
        print "Banner: IP Length OK"
      retorno=True
      
      if int (ipocts[0])==127 : return False
      for i in range(4):
        if(int(ipocts[i])<0 or int(ipocts[i])>255):
          if(self.debug>=2):
            print "Banner: Octeto "+ str(i) +" fuera de rango ["+ipocts[i]+"]"
          retorno=False          
          break
    else:
      retorno=False
    return retorno      

        
  def generateRandomIP(self):
    ip_old=self.ip
    ip=str(random.randint(0,255))+"."+str(random.randint(0,255))+"."+ str(random.randint(0,255))+"."+str( random.randint(0,255))
    self.ip=ip
    if(self.validIP()==True):
      self.ip=ip_old
      return ip
    else:
      self.ip=ip_old
      return self.generateRandomIP()
      
  def getNewRandomIP(self):
    self.setIP(self.generateRandomIP())
      
    
  def getHeader(self):
    try:
      conn=httplib.HTTPConnection(self.ip, self.port, timeout=1)
      conn.request("GET","/")
      conn.settimeout(1)
      r1 = conn.getresponse()
      self.responseHeader=r1.getheaders()
      data1=r1.read()    
      if(self.debug>=4):
        print r1.status, r1.reason
        print self.responseHeaders
        print data1
      conn.close()
    except KeyboardInterrupt:
      print "Exit by User"
    
  def __repr__(self):
    return "Banner: For IP: "+self.ip+" the headers are: "+self.responseHeaders  
    
  def __str__(self):
    return "Banner: For IP: "+self.ip+" the headers are: "+self.responseHeaders
    